Page({

  /**
   * 页面的初始数据
   */
  data: {
      title: '', // 分类标题
      shopList: [], // 商家列表
      page: 1,
      pagesize: 10,
      total: 0, // 总记录数
      isEnd: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      this.setData({
          title: options.title,
          id: options.id
      })

      // 获取商家列表数据
      this.getShopList()
  },
  
  getShopList(cb) {
      wx.showLoading({
          title: '加载中',
      })
      wx.request({
          url: `https://applet-base-api-t.itheima.net/categories/${this.data.id}/shops`,
          data: {
              _page: this.data.page,
              _pagesize: this.data.pagesize
          },
          success: (res) => {
              console.log(res)
              this.setData({
                  total: res.header['X-Total-Count'],
                  shopList: [...this.data.shopList, ...res.data]
              })
              wx.hideLoading()

              // 是否阻止下拉刷新的动作
              cb && cb()
          }
      })
  },

  /**
   * 用户点击商家项的处理函数
   */
  navigateToDetail(e) {
    const shopId = e.currentTarget.dataset.shopId;
    wx.navigateTo({
      url: `/pages/shopDetail/shopDetail?shopId=${shopId}`, // 确保路径正确
    });
  },

  onReady() {
      // 设置网页的导航标题
      wx.setNavigationBarTitle({
          title: this.data.title
      })
  },

  onPullDownRefresh() {
      this.setData({
              page: 1,
              shopList: []
          })
      this.getShopList(function() {
          wx.stopPullDownRefresh()
      })
  },

  onReachBottom() {
      if (this.data.page * this.data.pagesize >= this.data.total) {
          this.setData({
              isEnd: false
          })
          return wx.showToast({
              title: '没有更多数据了'
          })
      }

      this.setData({
          page: this.data.page + 1
      })

      this.getShopList()
  },

  onShareAppMessage() {

  }
})